<template>
  <div class="goods-sku">
    <template v-if="goods">
      <dl v-for="item in goods.specs" :key="item.name">
        <dt>{{ item.name }}</dt>
        <dd>
          <template v-for="val in item.values" :key="val.name">
            <img @click="changeSku(item, val)" v-if="val.picture"
              :class="{ selected: val.selected, disabled: val.disabled }" :src="val.picture" :title="val.name">
            <span @click="changeSku(item, val)" :class="{ selected: val.selected, disabled: val.disabled }" v-else>{{
                val.name
            }}</span>
          </template>
        </dd>
      </dl>
    </template>
  </div>
</template>
<script>
import powerSet from '@/vender/power-set'
const spliter = '★'
// 得到一个路径字典对象
const getPathMap = (skus) => {
  //1.得到说有的sku集合，  props.goods.skus
  //2.从所有的sku中筛选出有效的sku
  //3.根据所有有效的sku计算出所有子集
  //4.根据子集往径字典对象中存储key-value
  const pathMap = {}
  skus.forEach(sku => {
    if (sku.inventory > 0) {
      // 可选数组
      const valueArr = sku.specs.map(val => val.valueName)
      // 可选数组子集
      const valueArrPowerSet = powerSet(valueArr)
      // 遍历子集 往pathMap对象中添加
      valueArrPowerSet.forEach(arr => {
        const key = arr.join(spliter)
        if (pathMap[key]) {
          pathMap[key].push(sku.id)
        } else {
          pathMap[key] = [sku.id]
        }
      })
    }
  })
  return pathMap
}
const getSelectedValue = (specs) => {
  const arr = []
  specs.forEach(item => {
    const selectedVal = item.values.find(val => val.selected)
    arr.push(selectedVal ? selectedVal.name : undefined)
  })
  return arr
}
//更新选择规格的禁用状态
const updateDisabledStatus = (specs, pathMap) => {
  specs.forEach((item, i) => {
    const selectedValue = getSelectedValue(specs)
    item.values.forEach(val => {
      if (val.selected) return
      selectedValue[i] = val.name
      const key = selectedValue.filter(value => value).join(spliter)
      val.disabled = !pathMap[key]
    })
  })
}
//默认选中
const initDefaultSelected = (goods, skuId) => {
  //1.首先找出sku的信息
  //2.然后去遍历每个按钮
  const sku = goods.skus.find(item => item.id == skuId)
  goods.specs.forEach((item, i) => {
    const val = item.values.find(val => val.name == sku.specs[i].valueName)
    val.selected = true
  })
}

export default {
  name: 'GoodsSku',
  props: {
    goods: {
      type: Object,
      default: {}
    },
    skuId: {
      type: String,
      default: ''
    }
  },
  setup(props, { emit }) {
    // 调用getPathMap()方法
    const pathMap = getPathMap(props.goods.skus)
    //根据skuId初始化选中
    if (props.skuId) {
      initDefaultSelected(props.goods, props.skuId)
    }
    //初始化时更新规格按钮状态
    updateDisabledStatus(props.goods.specs, pathMap)

    const changeSku = (item, val) => {
      if (val.disabled) return
      //点击以选择的规格 取消当前的规格
      if (val.selected) {
        val.selected = false
      } else {
        item.values.forEach(itemval => {
          itemval.selected = false
          val.selected = true
        })
      }
      // 点击时更新规格按钮状态
      updateDisabledStatus(props.goods.specs, pathMap)
      //将选择的sku信息通知父组件{skuId,price,oldPrice,inventory,specsText}
      //1.选择完整的sku，才可以拿到这些信息，提交给父组件
      //2.不完整的sku ， 提交空对象给父组件
      const valiselectedValues = getSelectedValue(props.goods.specs).filter(v => v)
      if (valiselectedValues.length == props.goods.specs.length) {
        const skuIds = pathMap[valiselectedValues.join(spliter)]
        const sku = props.goods.skus.find(sku => sku.id === skuIds[0])
        emit('change',{
          skuId:sku.id,
          price:sku.price,
          oldPrice:sku.oldPrice,
          inventory:sku.inventory,
          specsText:sku.specs.reduce((p,c) =>`${p} ${c.name}: ${c.valueName}`,'').trim()
        }) 
      } else {
        emit('change', {})
      }
    }


    return {
      changeSku
    }
  }
}
</script>
<style scoped lang="less">
.sku-state-mixin () {
  border: 1px solid #e4e4e4;
  margin-right: 10px;
  cursor: pointer;

  &.selected {
    border-color: @xtxColor;
  }

  &.disabled {
    opacity: 0.6;
    border-style: dashed;
    cursor: not-allowed;
  }
}

.goods-sku {
  padding-left: 10px;
  padding-top: 20px;

  dl {
    display: flex;
    padding-bottom: 20px;
    align-items: center;

    dt {
      width: 50px;
      color: #999;
    }

    dd {
      flex: 1;
      color: #666;

      >img {
        width: 50px;
        height: 50px;
        .sku-state-mixin ();
      }

      >span {
        display: inline-block;
        height: 30px;
        line-height: 28px;
        padding: 0 20px;
        .sku-state-mixin ();
      }
    }
  }
}
</style>